package cc.ok200.muzhi;

import android.util.Log;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class WebSocketClient {
    private static final String TAG = "WebSocketClient";
    private static final long PING_INTERVAL = 5000; // ping间隔
    private static final long ACK_TIMEOUT = 8000; // 响应超时，8秒
    
    public static boolean isStarted = false;
    public static long lastAck = 0; // 最后一次收到服务器消息的时间戳
    
    private static org.java_websocket.client.WebSocketClient webSocketClient;
    private static Timer timer = new Timer();
    private static final Object lock = new Object();
    private static String serverUrl = "ws://192.168.1.200:8389"; // 服务器地址
    
    /**
     * 启动WebSocket客户端
     */
    public synchronized static void launch() {
        Log.d(TAG, "尝试启动WebSocketClient");
        if (isStarted) {
            Log.d(TAG, "WebSocketClient已经启动，无需重复启动");
            return;
        }
        isStarted = true;
        Log.d(TAG, "WebSocketClient启动成功，开始设置定时任务");
        
        // 计时器, 0秒后开始第一次执行，之后每秒循环一次
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.d(TAG, "执行连接检查：当前时间=" + System.currentTimeMillis() + ", 最后确认时间=" + lastAck);
                
                if (System.currentTimeMillis() - lastAck >= ACK_TIMEOUT) {
                    Log.d(TAG, "响应超时，尝试重新连接");
                    tryConnect();
                }
            }
        }, 0, 1000);
        
        // 计时器, 5秒后开始第一执行，之后每5秒循环一次
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (isConnected()) {
                    Log.d(TAG, "发送注册消息");
                    sendPing();
                } else {
                    Log.d(TAG, "连接未建立，跳过注册消息发送");
                }
            }
        }, PING_INTERVAL, PING_INTERVAL);
        
        Log.d(TAG, "WebSocketClient定时任务设置完成");
        tryConnect(); // 立即尝试第一次连接
    }
    
    /**
     * 检查WebSocket是否已连接
     */
    private static boolean isConnected() {
        // 只判断是否ACK超时
        return System.currentTimeMillis() - lastAck < ACK_TIMEOUT;
    }
    
    /**
     * 尝试连接WebSocket服务器
     */
    private static void tryConnect() {
        Log.d(TAG, "开始尝试连接WebSocket服务器");
        synchronized (lock) {
            // 强行清理旧资源
            closeConnection();
            
            try {
                Log.d(TAG, "创建新的WebSocket连接: " + serverUrl);
                URI uri = new URI(serverUrl);
                
                webSocketClient = new org.java_websocket.client.WebSocketClient(uri) {
                    @Override
                    public void onOpen(ServerHandshake handshakedata) {
                        Log.d(TAG, "WebSocket连接已打开，HTTP状态: " + handshakedata.getHttpStatus());
                        lastAck = System.currentTimeMillis();
                    }
                    
                    @Override
                    public void onMessage(String message) {
                        Log.d(TAG, "收到消息: " + message);
                        lastAck = System.currentTimeMillis();
                        
                        // 处理其他业务消息
                        handleMessage(message);
                    }
                    
                    @Override
                    public void onClose(int code, String reason, boolean remote) {
                        Log.d(TAG, "WebSocket连接已关闭: code=" + code + ", reason=" + reason + ", remote=" + remote);
                        lastAck = 0; // 连接断开，设置lastAck为0，触发重连
                    }
                    
                    @Override
                    public void onError(Exception ex) {
                        Log.e(TAG, "WebSocket连接发生错误", ex);
                        lastAck = 0; // 连接错误，设置lastAck为0，触发重连
                    }
                };
                
                Log.d(TAG, "设置WebSocket连接参数");
                webSocketClient.setConnectionLostTimeout(0); // 禁用库的自动重连
                webSocketClient.connectBlocking(5, TimeUnit.SECONDS); // 最多等待5秒连接
                
                if (webSocketClient.isOpen()) {
                    Log.d(TAG, "WebSocket连接成功建立");
                    lastAck = System.currentTimeMillis();
                } else {
                    Log.d(TAG, "WebSocket连接失败");
                    lastAck = 0;
                }
                
            } catch (URISyntaxException e) {
                Log.e(TAG, "WebSocket URI语法错误", e);
                lastAck = 0;
            } catch (InterruptedException e) {
                Log.e(TAG, "WebSocket连接被中断", e);
                lastAck = 0;
            } catch (Exception e) {
                Log.e(TAG, "WebSocket连接过程中发生未知错误", e);
                lastAck = 0;
            }
        }
    }
    
    /**
     * 向服务器发送注册事件
     */
    private static void sendPing() {
        try {
            String uuid = Storage.read(".uuid", "");
            if (uuid.isEmpty()) {
                Log.e(TAG, "无法获取设备UUID，跳过注册");
                return;
            }
            
            JSONObject msg = new JSONObject();
            msg.put("ping", uuid);
            
            String msgStr = msg.toString();
            Log.d(TAG, "发送注册事件: " + msgStr);
            webSocketClient.send(msgStr);
        } catch (JSONException e) {
            Log.e(TAG, "构建注册消息失败", e);
        } catch (Exception e) {
            Log.e(TAG, "发送注册消息失败", e);
        }
    }
    
    /**
     * 关闭现有WebSocket连接
     */
    private static void closeConnection() {
        synchronized (lock) {
            if (webSocketClient != null) {
                try {
                    Log.d(TAG, "正在关闭旧的WebSocket连接");
                    webSocketClient.close();
                } catch (Exception e) {
                    Log.e(TAG, "关闭WebSocket连接时发生错误", e);
                } finally {
                    webSocketClient = null;
                    Log.d(TAG, "旧的WebSocket连接资源已清理");
                }
            }
        }
    }
    
    /**
     * 发送消息到WebSocket服务器
     */
    public static boolean send(String message) {
        synchronized (lock) {
            if (isConnected() && webSocketClient != null && webSocketClient.isOpen()) {
                try {
                    Log.d(TAG, "发送消息: " + message);
                    webSocketClient.send(message);
                    return true;
                } catch (Exception e) {
                    Log.e(TAG, "发送消息失败", e);
                    lastAck = 0; // 发送失败，可能连接已断开，设置lastAck为0触发重连
                    return false;
                }
            } else {
                Log.d(TAG, "连接未建立，无法发送消息: " + message);
                return false;
            }
        }
    }
    
    /**
     * 处理接收到的业务消息
     */
    private static void handleMessage(String message) {
        // 处理接收到的业务消息，根据实际需求实现
        Log.d(TAG, "处理业务消息: " + message);
    }
    
    /**
     * 停止WebSocket客户端
     */
    public synchronized static void stop() {
        Log.d(TAG, "停止WebSocketClient");
        if (!isStarted) {
            Log.d(TAG, "WebSocketClient未启动，无需停止");
            return;
        }
        
        timer.cancel();
        timer = new Timer();
        closeConnection();
        isStarted = false;
        lastAck = 0;
        Log.d(TAG, "WebSocketClient已停止");
    }
    
    /**
     * 设置WebSocket服务器地址
     */
    public static void setServerUrl(String url) {
        serverUrl = url;
        Log.d(TAG, "设置WebSocket服务器地址: " + url);
    }
} 